/*------------------------------------------------------------------------
//                          Project CommonLib                           //
------------------------------------------------------------------------*/

#include "stdafx.h"
#include "KeyGen.h"
    
KeyGen::KeyGen(const DWORD& dwMax)
    :m_lPosition(0), m_lMax(dwMax)
{
    m_pKeyBuffer = CmNEW char[ m_lMax/8+1 ];
    ZeroMemory( m_pKeyBuffer, m_lMax/8+1 );
}
    
KeyGen::~KeyGen()
{
    CmSAFE_DELETES( m_pKeyBuffer);
}

    
int KeyGen::ReserveKey()
{
    for( DWORD i=0; i<m_lMax; ++i)
    {
        if( !CHECKBIT( (char*)m_pKeyBuffer, GetNext() ) )
        {
            SETBIT( (char*)m_pKeyBuffer, GetPos() );
            return GetPos();
        }
    }
    return -1;
}
    
BOOL KeyGen::ReleaseKey( const int& nkey)
{
    if( CHECKBIT( m_pKeyBuffer, nkey ) )
    {
        UNSETBIT( m_pKeyBuffer, nkey );
        return TRUE;
    }
    return FALSE;
}

    
long KeyGen::GetPos() 
{
    return m_lPosition;
}

long KeyGen::GetNext()
{
    if( (m_lMax)<=m_lPosition )
    {
        m_lPosition=0;

    }
    return ++m_lPosition;
}

void KeyGen::Reset()
{
	ZeroMemory( m_pKeyBuffer, m_lMax/8+1 );
}



/*------------------------------------------------------------------------

------------------------------------------------------------------------*/
